package cn.edu.swu.mhans.web.controller;

import cn.edu.swu.mhans.user.model.SystemUser;
import cn.edu.swu.mhans.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author ZhanJingbo
 * @version 1.0.0
 * Created on 2018/4/23
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String loginPage() {
        return "login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String registerPage() {
        return "register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String handleRegister(SystemUser systemUser) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(systemUser.getPassword());
        systemUser.setPassword("{bcrypt}" + password);
        boolean result = userService.register(systemUser);
        if (!result) {
            throw new RuntimeException("error");
        }
        return "redirect:/login";
    }
}
